package ui;

import javafx.animation.*;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.BoxBlur;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
import utils.DBUtil;

public class MenuPage extends Application {

    @Override
    public void start(Stage primaryStage) {
        // 创建主容器
        StackPane root = new StackPane();
        root.setAlignment(Pos.CENTER);

        // ==================== 修改点1：背景面板改为图片背景 ====================
        Pane backgroundPane = new Pane();
        try {
            // 从resources/images加载背景图
            Image bgImage = new Image(getClass().getResourceAsStream("/images/AI.jpg"));
            BackgroundImage backgroundImg = new BackgroundImage(
                    bgImage,
                    BackgroundRepeat.NO_REPEAT,
                    BackgroundRepeat.NO_REPEAT,
                    BackgroundPosition.CENTER,
                    new BackgroundSize(
                            100, 100,
                            true, true,
                            false, true
                    )
            );
            backgroundPane.setBackground(new Background(backgroundImg));
        } catch (Exception e) {
            System.err.println("背景图片加载失败: " + e.getMessage());
            // 备用方案：纯色背景
            backgroundPane.setStyle("-fx-background-color: #2D3447;");
        }
        // ==================== 修改点结束 ====================

        // 创建背景遮罩（保持原有半透明效果）
        Rectangle overlay = new Rectangle();
        overlay.getStyleClass().add("background-overlay");
        overlay.widthProperty().bind(root.widthProperty());
        overlay.heightProperty().bind(root.heightProperty());
        overlay.setFill(Color.rgb(13, 20, 41, 0.5)); // 调整为深蓝色调

        // 添加模糊效果（作用在遮罩层上）
        BoxBlur blur = new BoxBlur(5, 5, 3);
        overlay.setEffect(blur);

        // 创建内容容器（以下保持原有代码不变）
        VBox contentBox = new VBox(40);
        contentBox.setAlignment(Pos.CENTER);
        contentBox.setPadding(new Insets(50));
        contentBox.setMaxWidth(800);

        // 创建标题
        Text title = new Text("冷链承运商全场景可视化SOP系统");
        title.getStyleClass().add("menu-title");

        // 创建按钮容器
        VBox buttonBox = new VBox(20);
        buttonBox.setAlignment(Pos.CENTER);
        buttonBox.getStyleClass().add("button-container");
        buttonBox.setMaxWidth(400);

        // 创建功能按钮
        Button[] buttons = {
                createMenuButton("客户信息", () -> switchScene(primaryStage, new CustomerListPage())),
                createMenuButton("分组管理", () -> switchScene(primaryStage, new GroupListPage())),
                createMenuButton("运输要求", () -> {
                    new RequirementListPage(primaryStage).show();
                }),
                createMenuButton("运输明细", () -> {
                    new ComingSoonPage().show(primaryStage);
                }),
                createMenuButton("模板管理", () -> {
                    new TemplateManagePage().start(primaryStage);
                }),
                createMenuButton("退出系统", () -> {
                    FadeTransition fadeOut = new FadeTransition(Duration.seconds(0.3), root);
                    fadeOut.setFromValue(1.0);
                    fadeOut.setToValue(0.0);
                    fadeOut.setOnFinished(e -> Platform.exit());
                    fadeOut.play();
                }),

        };

        // 添加按钮到容器
        buttonBox.getChildren().addAll(buttons);

        // 添加所有元素到内容容器
        contentBox.getChildren().addAll(title, buttonBox);

        // 按照层次添加所有组件（注意顺序：背景在最下层）
        root.getChildren().addAll(backgroundPane, overlay, contentBox);

        // 创建场景
        Scene scene = new Scene(root, 1300, 900);
        scene.getStylesheets().add("/css/menu.css");

        // 设置窗口
        primaryStage.setTitle("冷链物流管理系统");
        primaryStage.setScene(scene);
        primaryStage.show();

        // 添加入场动画
        playEntranceAnimation(contentBox);
    }

    // ============= 以下方法保持不变 =============
    private Button createMenuButton(String text, Runnable action) {
        Button button = new Button(text);
        button.getStyleClass().add("menu-button");
        button.setOnAction(e -> action.run());
        return button;
    }

    private void playEntranceAnimation(VBox content) {
        // 设置初始状态
        content.setOpacity(0);
        content.setTranslateY(40);
        content.setScaleX(0.92);
        content.setScaleY(0.92);

        // 创建动画
        ParallelTransition parallelTransition = new ParallelTransition();

        // 淡入动画
        FadeTransition fadeIn = new FadeTransition(Duration.seconds(1.2), content);
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        fadeIn.setInterpolator(Interpolator.SPLINE(0.215, 0.61, 0.355, 1.0));

        // 上移动画
        TranslateTransition translateIn = new TranslateTransition(Duration.seconds(1.2), content);
        translateIn.setFromY(40);
        translateIn.setToY(0);
        translateIn.setInterpolator(Interpolator.SPLINE(0.165, 0.84, 0.44, 1.0));

        // 缩放动画
        ScaleTransition scaleIn = new ScaleTransition(Duration.seconds(1.2), content);
        scaleIn.setFromX(0.92);
        scaleIn.setFromY(0.92);
        scaleIn.setToX(1);
        scaleIn.setToY(1);
        scaleIn.setInterpolator(Interpolator.SPLINE(0.19, 1.0, 0.22, 1.0));

        parallelTransition.getChildren().addAll(fadeIn, translateIn, scaleIn);

        // 添加延迟启动
        PauseTransition delay = new PauseTransition(Duration.seconds(0.1));
        SequentialTransition sequence = new SequentialTransition(delay, parallelTransition);
        sequence.play();
    }

    private void switchScene(Stage stage, Object page) {
        if (page instanceof CustomerListPage) {
            CustomerListPage customerListPage = (CustomerListPage) page;
            customerListPage.start(new Stage());
        } else if (page instanceof Application) {
            try {
                ((Application) page).start(new Stage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        stage.close();
    }

    public static void main(String[] args) {
        DBUtil.createTableIfNotExists();
//        MockData.generateMockLogisticsData(10);
        System.out.println("表已创建或已存在！");
        launch(args);
    }
}